package com.ng.biz.controller;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.ng.biz.model.domain.MqttClient;
import com.ng.biz.service.IMqttClient;
import com.ng.common.annotation.TokenRequired;
import com.ng.common.annotation.Tx;
import com.ng.common.controller.Controller;
import com.ng.common.model.response.R;
import com.ng.common.util.UuidUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

@Tag(name = "MQTT数据管理")
@RequiredArgsConstructor
@RestController
@RequestMapping("/biz/mqtt")
public class MqttClientController extends Controller {
	
    @Autowired
    private IMqttClient mqttClientImpl;

	// 提取常量
	private static final String ORDER_BY_CREATE_TIME_DESC = " ORDER BY a.create_time desc ";
	private static final String SELECT_ALL = "select a.* ";

	@Operation(summary = "分页获取MQTT客户端列表")
	@Parameters({ @Parameter(name = "keywords", description = "关键字", required = false),
			@Parameter(name = "cur", description = "当前页码", required = true),
			@Parameter(name = "limit", description = "每页数据量", required = true) })
	@TokenRequired
	@GetMapping("/pages")
	public R<Page<MqttClient>> pages(HttpServletRequest request,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) {

		StringBuilder sqlExceptSelect = new StringBuilder().append(" from ").append(MqttClient.TABLE_NAME)
				.append(" a WHERE 1=1 ");

		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect.append(" and (a.name like '%").append(keywords).append("%'").append(" or a.host like '%")
					.append(keywords).append("%') ");
		}
		sqlExceptSelect.append(ORDER_BY_CREATE_TIME_DESC);
		
		Page<MqttClient> page=MqttClient.dao.paginate(cur, limit, SELECT_ALL, sqlExceptSelect.toString());
		for(MqttClient mqttClient:page.getList()) {
			mqttClient.setIsRunning(mqttClientImpl.containsKey(mqttClient.getId())?"1":"0");
		}
		return R.ok(page);
	}

	@Operation(summary = "获取MQTT客户端列表")
	@Parameters({ @Parameter(name = "keywords", description = "关键字", required = false) })
	@TokenRequired
	@GetMapping("/options")
	public R<List<MqttClient>> options(HttpServletRequest request,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords) {
		try {
			StringBuilder sql = new StringBuilder().append(SELECT_ALL).append(" from ").append(MqttClient.TABLE_NAME)
					.append(" a WHERE 1=1 ");

			if (!StrKit.isBlank(keywords)) {
				sql.append(" and (a.name like '%").append(keywords).append("%'").append(" or a.host like '%")
						.append(keywords).append("%') ");
			}
			sql.append(ORDER_BY_CREATE_TIME_DESC);
			return R.ok(MqttClient.dao.find(sql.toString()));
		} catch (Exception e) {
			return R.failed("获取列表失败: " + e.getMessage());
		}
	}
	

	@Operation(summary = "保存MQTT客户端")
	@TokenRequired
	@Tx
	@PostMapping("/save")
	public R<MqttClient> save(HttpServletRequest request, @RequestBody MqttClient mqttClient) {
		try {
			Date now = new Date(System.currentTimeMillis());
			String userId = getUserId(request);

			if (StrKit.notBlank(mqttClient.getId())) {
				return updateMqttClient(mqttClient, userId, now);
			} else {
				return createMqttClient(mqttClient, userId, now);
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	// 抽取更新方法
	private R<MqttClient> updateMqttClient(MqttClient mqttClient, String userId, Date updateTime) {
		mqttClient.setUpdateUserId(userId);
		mqttClient.setUpdateTime(updateTime);
		return mqttClient.update() ? R.ok(mqttClient) : R.failed("更新失败！");
	}

	// 抽取创建方法
	private R<MqttClient> createMqttClient(MqttClient mqttClient, String userId, Date createTime) {
		mqttClient.setId(UuidUtil.getUUID());
		mqttClient.setCreateUserId(userId);
		mqttClient.setCreateTime(createTime);
		return mqttClient.save() ? R.ok(mqttClient) : R.failed("保存失败.");
	}

	@Operation(summary = "删除MQTT客户端")
	@Parameters({ @Parameter(name = "ids", description = "MQTT客户端id集合(逗号分割)", required = true) })
	@TokenRequired
	@DeleteMapping("/{ids}")
	public R<String> delete(@PathVariable("ids") String ids) {
		if (StrKit.isBlank(ids)) {
			return R.failed("请选择需要删除的客户端.");
		}

		try {
			for (String id : ids.split(",")) {
				if (!MqttClient.dao.deleteById(id)) {
					return R.failed("删除失败: " + id);
				}
				mqttClientImpl.stop(id);
			}
			return R.ok();
		} catch (Exception e) {
			return R.failed("删除失败: " + e.getMessage());
		}
	}

	@Operation(summary = "启动MQTT客户端")
	@Parameters({ @Parameter(name = "id", description = "客户端Id", required = true) })
	@TokenRequired
	@PostMapping("/start/{id}")
	public R<String> start(@PathVariable("id") String id) {
		try {
			return mqttClientImpl.start(id);
		} catch (Exception e) {
			return R.failed("启动失败: " + e.getMessage());
		}
	}

	@Operation(summary = "停止MQTT客户端")
	@Parameters({ @Parameter(name = "id", description = "客户端Id", required = true) })
	@TokenRequired
	@PostMapping("/stop/{id}")
	public R<Boolean> stop(@PathVariable("id") String id) {
		try {
			mqttClientImpl.stop(id);
			return R.ok(true);
		} catch (Exception e) {
			return R.failed("停止失败: " + e.getMessage());
		}
	}
}
